package com.wangyadong.hobby.schedule.jobtask.javasync.cyclicbarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/1/719:32
 **/
public class CyclicBarrierExample1 {
    /**
     * 分成2组
     * 但是有三次 await 会一直阻塞
     * @param args
     * @throws BrokenBarrierException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

        new Thread() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    System.out.println("T1 finshed");
                    cyclicBarrier.await();
                    System.out.println("T1 the other thread finshed too.  " +
                            " ");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }.start();


        new Thread() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    System.out.println("T2 finshed");
                    cyclicBarrier.await();
                    System.out.println("T2 the other thread finshed too.  " +
                            " ");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        System.out.println(cyclicBarrier.getNumberWaiting());
        System.out.println(cyclicBarrier.getParties());
        System.out.println(cyclicBarrier.isBroken());
        System.out.println("=================================");
        cyclicBarrier.await();
    }
}
